import { GetTables, syncColumns, genOrDownload, gen } from '@/services/systemUtil/codeUtil';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Select, Switch, Transfer, notification } from 'antd';
import type { TransferDirection } from 'antd/es/transfer';
import { history } from 'umi';
import React, { useEffect, useReducer, useRef, useState } from 'react';
import {
  roleFormInit,
  roleFormReducer,
  userFormInit,
  userFormReducer,
} from '../system/userReducer';
import DebounceSelect from '@/components/DebounceSelect';
const { Option } = Select;

// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}

const CodeUtil: React.FC<{}> = () => {
  // 表单弹框信息
  const [userFormState, userdispatch] = useReducer(userFormReducer, userFormInit);

  // 绑定角色信息弹框
  const [roleFormState, roledispatch] = useReducer(roleFormReducer, roleFormInit);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [value, setValue] = useState<UserValue[]>([]);

  const [formVisit, setFormVisit] = useState(false); // 新建和编辑提示框
  const [formTitle, setFormTitle] = useState('重置密码'); // 标题
  const [confirmLoading3, setConfirmLoading3] = useState(false); //加载

  // 绑定客户信息
  const [customerData, setCustomerData] = useState<object[]>([{ id: '', name: '' }]);

  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable

  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable
  const onChange = (nextTargetKeys: string[], direction: TransferDirection, moveKeys: string[]) => {
    roledispatch({ type: 'onchange', targetKeys: nextTargetKeys });
  };

  // const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
  //   console.log('sourceSelectedKeys:', sourceSelectedKeys);
  //   console.log('targetSelectedKeys:', targetSelectedKeys);
  //   setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  // };

  const onScroll = (direction: TransferDirection, e: React.SyntheticEvent<HTMLUListElement>) => {
    console.log('direction:', direction);
    console.log('target:', e.target);
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '表名', //表头显示的名称
      dataIndex: 'tableName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '编号', //表头显示的名称
      dataIndex: 'coding',
    },

    // {
    //   title: '客户名称', //表头显示的名称
    //   hideInTable: true,
    //   dataIndex: 'customerName',
    // },
    // {
    //   title: '昵称', //表头显示的名称
    //   search: false,
    //   dataIndex: 'nickName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    // },
    {
      title: '引擎', //表头显示的名称
      search: false,
      dataIndex: 'engine', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '备注', //表头显示的名称
      search: false,
      dataIndex: 'remark', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            userdispatch({ type: 'update' });
            form.setFieldsValue({
              name: record.name,
              id: record.id,
              email: record.email,
              phone: record.phone,
              gender: record.gender,
              customerId: record.customerName,
            });
          }}
        >
          预览
        </a>,
        <a
          key="updatePassword"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            // console.log(record, '---record---');
            genOrDownload({
              tableName: record.tableName,
              type: 2,
            })
              .then(async (res) => {
                console.log(res, '--res-');
                if (res?.size >= 200) {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);
                  aLink.setAttribute('download', `${record.tableName}.zip`);
                  aLink.click();
                  document.body.removeChild(aLink);
                } else {
                  const result = await res.text();
                  const json = JSON.parse(result);
                  console.log(json, '--res-');
                  notification.error({
                    description: json.data,
                    message: json.message,
                  });
                }
              })
              .catch((error) => {
                console.log(error, '---error---');
              });
          }}
        >
          下载
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            roledispatch({ type: 'setUserId', userId: record.id });
            // actionRef.current.reload();
            // setDeleteVisit(true);
            history.push({
              pathname: `/systemSetting/systemUtil/tableConfig`,
              query: {
                tableName: record.tableName,
              },
            });
            // actionRef.current.reload();
          }}
        >
          配置
        </a>,

        <a
          key="linkRole"
          onClick={async () => {
            await gen({
              tableName: record.tableName,
              type: 0,
            });
          }}
        >
          生成
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (userFormState.title == '新建用户') {
      const result = await AddUser(form.getFieldsValue());
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateUser(form.getFieldsValue());
    }
    setConfirmLoading(false);
    userdispatch({ type: 'close' });
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const handleSubmit2 = async () => {
    setConfirmLoading3(true);
    await updatePassword(form2.getFieldsValue());
    setConfirmLoading3(false);
    setFormVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const onGenderChange = (value: string) => {};

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable //表格Pro组件
        headerTitle="用户创建表格" //表头
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="tableName" //表格行 key 的取值，可以是字符串或一个函数
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={async () => {
              console.log(selectedRows, '---选取多行----');
              // 1.清空form
              const tables = selectedRows.map((item) => item.tableName);
              await syncColumns(tables);
              //
            }}
            type="primary"
          >
            同步
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          console.log(params, sort, filter);
          const result = await GetTables(params);
          console.log(result);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
          // return  await new Promise({data:[{loginName:}], total:10, success: 0})
          // return {data:[], total:10, success: 0}
        }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
        columns={columns} //上面定义的
        pagination={{
          defaultPageSize: 100,
          defaultCurrent: 1,
          pageSizeOptions: [100, 500, 1000],
          showSizeChanger: true,
        }}
        scroll={{ y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={userFormState.title}
        visible={userFormState.visit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => userdispatch({ type: 'close' })}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="用户名"
            name="name"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input disabled={userFormState.createOrUpdate} />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            hidden={userFormState.createOrUpdate}
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item name={'email'} label="邮箱" rules={[{ type: 'email' }]}>
            <Input />
          </Form.Item>
          <Form.Item name={'phone'} label="电话">
            <Input />
          </Form.Item>

          <Form.Item name={'gender'} label="性别">
            <Select>
              <Option value="0">男</Option>
              <Option value="1">女</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={formTitle}
        visible={formVisit}
        onOk={handleSubmit2}
        confirmLoading={confirmLoading3}
        onCancel={() => {
          setFormVisit(false);
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form2}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="绑定角色"
        visible={roleFormState.visit}
        confirmLoading={confirmLoading2}
        onOk={async () => {
          setConfirmLoading2(true);
          await saveRolesByUserId({
            userId: roleFormState.userData.id,
            rolesId: roleFormState.targetKeys,
          });
          actionRef.current.reload();
          setConfirmLoading2(false);
          roledispatch({ type: 'close' });
        }}
        onCancel={() => {
          roledispatch({ type: 'close' });
        }}
      >
        <Transfer
          dataSource={roleFormState.rolesData}
          titles={['未选', '已选']}
          targetKeys={roleFormState.targetKeys}
          onChange={onChange}
          onScroll={onScroll}
          render={(item) => item.title}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default CodeUtil;
